module.exports = {
  /**
   * 获取问卷
  */
  async getPapers(req) {
    const count = await req.papersModel.getPapersCount();
    const result = await req.papersModel.getPapers(req.query);
    return {
      count,
      result,
    };
  },
  /**
   * 添加
  */
  async addPaper(req, { boom }) {
    const {
      papername,
    } = req.payload;
    const papernameExist = await req.papersModel.isExist('papername', papername);
    if (papernameExist) {
      return boom.badRequest('问卷名已存在');
    }
    const result = await req.papersModel.addPapers(req.payload);
    return result;
  },

  /**
   * 根据ID获取单个问卷信息
   */
  async getPaperById(req) {
    const result = await req.papersModel.getPaperById(req.params.id);
    return result;
  },

  /**
   * 根据ID删除问卷
   */
  async deletePaperById(req) {
    await req.papersModel.deletePaperById(req.params.id);
    return {};
  },
  /**
   * 根据多个ID批量删除问卷
  */
  async deletePapersByIds(req) {
    await req.papersModel.deletePapersByIds(req.payload.ids);
    return {};
  },

  /**
   * 根据ID更新问卷信息
  */
  async updatePaperById(req) {
    await req.papersModel.updatePaperById(req.params.id, req.payload);
    return {};
  },
  /**
   * 编辑登陆问卷信息
  */
  async updatePaperLogined(req, { boom }) {
    const {
      papername,
    } = req.payload;
    const page = await req.papersModel.getPaperById(req.params.id);
    if (page.papername !== papername) {
      const papernameExist = await req.papersModel.isExist('papername', papername);
      if (papernameExist) {
        return boom.badRequest('问卷名已存在');
      }
    }
    await req.papersModel.updatePaperById(req.auth.credentials.uid, req.payload);
    return {};
  },
  /**
   * 判断字段值是否存在
  */
  async isExist(req) {
    const { field, value } = req.query;
    const result = await req.papersModel.isExist(field, value);
    return Boolean(result);
  },
};
